<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addroles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" style="width: 100%" stripe border>
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-row
              :class="['bb', i1 == 0 ? 'bt' : '', 'ccenter']"
              v-for="(item1, i1) in row.children"
              :key="item1.id"
            >
              <!-- 一级权限列表 -->
              <el-col :span="8">
                <el-tag closable @close="delet(row.id, item1.id)">{{
                  item1.authName
                }}</el-tag
                ><span class="el-icon-caret-right"></span>
              </el-col>
              <!-- 二三级权限列表 -->
              <el-col :span="16">
                <el-row
                  :class="[i2 === 0 ? '' : 'bt', 'ccenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="12"
                    ><el-tag
                      closable
                      @close="delet(row.id, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <span class="el-icon-caret-right"></span>
                  </el-col>
                  <el-col :span="12">
                    <el-tag
                      closable
                      @close="delet(row, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <!-- {{ row.id }} -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="changerole1(row.id)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delbyid(row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              @click="shuxingtu(row)"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="shuxing"
        width="30%"
        @close="cleararr"
      >
        <span>
          <!-- 树形控件对话框 -->
          <el-tree
            ref="shu"
            :data="list"
            :props="treeprop"
            show-checkbox
            default-expand-all
            node-key="id"
            :default-checked-keys="shuarr"
          ></el-tree>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="shuxing = false">取 消</el-button>
          <el-button type="primary" @click="addquanxian">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addrolefalg" width="30%">
        <span>
          <el-form
            :model="addrole"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addrole.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addrole.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addrolefalg1">取 消</el-button>
          <el-button type="primary" @click="addrolese">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色对话框 -->

      <el-dialog title="修改角色" :visible.sync="changerolefalg" width="30%">
        <span>
          <el-form
            :model="changerole"
            :rules="rules"
            ref="changeruleForm"
            label-width="100px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="changerole.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="changerole.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="changerolefalg1">取 消</el-button>
          <el-button type="primary" @click="changerolese">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      shuxing: false,
      rolelist: [],
      // 树形结构数据
      list: [],
      // 定义点击的树形图id
      shuid: '',
      //树形默认选中的数组
      shuarr: [],
      // 树形控件
      treeprop: {
        children: 'children',
        label: 'authName'
      },
      // 添加角色对象
      addrole: {
        roleName: '',
        roleDesc: ''
      },
      //添加角色开关对话框
      addrolefalg: false,
      //修改角色id
      changeid: '',
      // 修改角色对象
      changerole: {},
      changerolefalg: false,
      //开关属性
      // flag: true,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  // mounted () {},
  computed: {},
  watch: {},
  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolelist = res.data
      // console.log(this.rolelist);
    },
    // 根据id删除用户权限
    async delet(row, id2) {
      console.log(row, id2)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err) // 如果用户确认删除，则返回值为字符串 confirm // 如果用户取消了删除，则返回值为字符串 cancel // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      //删除后续操作
      const { data: res } = await this.$http.delete(
        `roles/${row.id}/rights/${id2}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      row.children = res.data
      this.$message.success('删除成功')
    },
    // 树形图
    async shuxingtu(row) {
      this.shuxing = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status != 200) return
      // 获取树形图数据定义到data中
      this.list = res.data
      //获取角色id定义到data中
      this.shuid = row.id
      // 调用递归函数往数组中添加数据
      this.digui(row, this.shuarr)
    },
    // 定义一个递归函数保存三级节点的id值
    digui(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.digui(item, arr)
      })
    },
    // 关闭对话框清空数组内的id
    cleararr() {
      this.shuarr = []
      // console.log(this.shuarr);
    },
    // 点击确定按钮拿到全选和半选的id值发请求修改后台数据
    async addquanxian() {
      // 拿到接口数据
      const keys = [
        ...this.$refs.shu.getCheckedKeys(),
        ...this.$refs.shu.getHalfCheckedKeys()
      ]
      // 发送请求修改用户权限
      const { data: res } = await this.$http.post(
        `roles/${this.shuid}/rights`,
        { rids: keys.join(',') }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('授权失败,稍后重试')
      }
      this.$message.success('授权成功')
      this.getRolesList()
      // console.log(res);
      this.shuxing = false
    },
    //点击删除按钮删除角色通过id
    async delbyid(id) {
      //询问框
      const data = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(data);
      if (data !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除逻辑
      const { data: res } = await this.$http.delete(`roles/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败,稍后重试')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    },
    // 弹出添加角色对话框
    async addroles() {
      this.addrolefalg = true
    },
    //点击确定提交添加角色数据
    async addrolese() {
      // 规则验证
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        //this.addrole为data中和表单双向绑定的数据
        const { data: res } = await this.$http.post('roles', this.addrole)
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功')
        // 清空数据
        this.addrole = {}
        // 关闭对话框
        this.addrolefalg = false
        //重新加载页面
        this.getRolesList()
      })
    },
    //点击取消重置表达验证规则并关闭对话框
    addrolefalg1() {
      this.$refs.ruleForm.resetFields()
      this.addrolefalg = false
    },
    // 点击修改获取修改角色根据id
    async changerole1(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return
      // 数据赋值注意这里是对象的直接覆盖,其他方法会出问题.亲测!!!
      this.changerole = res.data
      //保存传递的id,修改时会用到
      this.changeid = id
      //弹出修改角色的对话框
      this.changerolefalg = true
    },
    //点击确定修改角色
    async changerolese() {
      const { data: res } = await this.$http.put(
        `roles/${this.changeid}`,
        this.changerole
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户失败！')
      }
      this.$message.success('修改用户成功')
      // 清空data中的数据
      this.changerole = {}
      //关闭对话框
      this.changerolefalg = false
      // 重新加载数据
      this.getRolesList()
    },
    //点击取消重置表达验证规则
    changerolefalg1() {
      this.$refs.changeruleForm.resetFields()
      //关闭对话框
      this.changerolefalg = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bb {
  border-bottom: 1px solid #cccccc;
}
.bt {
  border-top: 1px solid #cccccc;
}
.ccenter {
  display: flex;
  align-items: center;
}
</style>
